package com.example.testjenkins.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling().accessDeniedPage("/403.html");

        http.formLogin()
                .loginPage("/login.html")

                .loginProcessingUrl("/login")
                .defaultSuccessUrl("/test2").permitAll()
                .and().authorizeRequests()
                .antMatchers("/login", "/swagger-ui/*").permitAll()
//                .antMatchers().hasAnyAuthority("ad")
//                .antMatchers("/test*").hasAnyRole("ad")
                .anyRequest().authenticated()
                .and().rememberMe().userDetailsService(userDetailsService)
                .and().csrf().disable();

        http.logout().logoutUrl("/logout").logoutSuccessUrl("/login.html").permitAll();
    }
}
